//
//  ViewController.m
//  MyMusic
//
//  Created by ioser on 17/5/3.
//  Copyright © 2017年 ioser. All rights reserved.
//

#import "ViewController.h"
#import "Masonry.h"
#import "GetMusicTool.h"
#import "MusicInfoModel.h"
#import "playMusicTool.h"
#import <AVFoundation/AVFoundation.h>
#import "NSString+MusicTimeCalculate.h"
#import "CALayer+PauseAimate.h"
#import "MusicLrcsScrollerView.h"
#import "LrcsLable.h"
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *albumImageView;
@property (weak, nonatomic) IBOutlet UISlider *sliderView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *musicNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *currenTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playorPauseButton;
@property (weak, nonatomic) IBOutlet LrcsLable *LrcsLabel;



@property (strong, nonatomic)AVAudioPlayer *player;
@property (strong, nonatomic)NSTimer *slideTimer;
@property (strong, nonatomic)CADisplayLink *lrcsTimer;
@property (weak, nonatomic) IBOutlet MusicLrcsScrollerView *LrcsScrollerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTabBar];
    
    [self setupSliderView];
    
    [self playCurrentMusic];
    
    self.LrcsScrollerView.delegate = self;
    
    __weak typeof(self) weakSelf = self;
    [self.LrcsScrollerView setLrcBlock:^(CGFloat progress, NSString *text) {
//        NSLog(@"%f %@",progress,text);
        weakSelf.LrcsLabel.text = text;
        weakSelf.LrcsLabel.progress = progress;
    }];
    
//    NSLog(@"增加了git功能");
}



#pragma mark - 播放当前音乐
- (void)playCurrentMusic
{
    
    // 1 通过工具类获取当前播放音乐的数据模型
    MusicInfoModel *currentMusicModel = [GetMusicTool returnPlayingMusic];

    // 2 给控件绑数据
    self.albumImageView.image = [UIImage imageNamed:currentMusicModel.icon];
    self.iconImageView.image = [UIImage imageNamed:currentMusicModel.icon];
    self.musicNameLabel.text = currentMusicModel.name;
    self.singerNameLabel.text = currentMusicModel.singer;
    // 2.1 传递歌词名
    self.LrcsScrollerView.LrcFileName = currentMusicModel.lrcname;
    
    // 3 根据音乐文件 在 工具类里播放音乐
    AVAudioPlayer *player = [playMusicTool playMusicWithName:currentMusicModel.filename];
    self.player = player;
    
    self.playorPauseButton.selected = [self.player isPlaying];
    
    
    // 4 添加定时器
    [self removerTimer];
    [self addTimer];
    
    [self removeLrcsTimer];
    [self addLrcsTimer];
    
    // 5 设置进度条时间
    self.currenTimeLabel.text = [NSString intervalWithTime:player.currentTime];
    self.totalTimeLabel.text = [NSString intervalWithTime:player.duration];
    
    // 6 设置头像的旋转动画
    [self addTransformAnimation];
    
    [self setupLockScreen];
}

- (void)setupLockScreen
{
    // MPMediaItemPropertyAlbumTitle
    // MPMediaItemPropertyAlbumTrackCount
    // MPMediaItemPropertyAlbumTrackNumber
    // MPMediaItemPropertyArtist
    // MPMediaItemPropertyArtwork
    // MPMediaItemPropertyComposer
    // MPMediaItemPropertyDiscCount
    // MPMediaItemPropertyDiscNumber
    // MPMediaItemPropertyGenre
    // MPMediaItemPropertyPersistentID
    // MPMediaItemPropertyPlaybackDuration
    // MPMediaItemPropertyTitle

    MusicInfoModel *currenMusic = [GetMusicTool returnPlayingMusic];
    
    // 获取锁屏中心
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    // 锁屏界面歌曲名
    [infoDic setObject:currenMusic.name forKey:MPMediaItemPropertyAlbumTitle];
    // 锁屏界面歌手名
    [infoDic setObject:currenMusic.singer forKey:MPMediaItemPropertyArtist];
    // 锁屏界面图片
    MPMediaItemArtwork *Artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:currenMusic.icon]];
    [infoDic setObject:Artwork forKey:MPMediaItemPropertyArtwork];
    // 总时长
    [infoDic setObject:@(self.player.duration) forKey:MPMediaItemPropertyPlaybackDuration];
    infoCenter.nowPlayingInfo = infoDic;
    
    
    // 开始远程交互
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)addTransformAnimation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.duration = 35;
    animation.fromValue = @0;
    animation.toValue = @(M_PI * 2);
    animation.repeatCount = NSIntegerMax;
    [self.iconImageView.layer addAnimation:animation forKey:@"iconAnimation"];
}

#pragma mark - scrollView 代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offX = scrollView.contentOffset.x;
    CGFloat ratio = 1 - offX / scrollView.frame.size.width;
    self.LrcsLabel.alpha = ratio;
    self.iconImageView.alpha = ratio;
}


// 设置滑动条
- (void)setupSliderView
{
    UIImage *image = [UIImage imageNamed:@"player_slider_playback_thumb"];
    [self.sliderView setThumbImage:image forState:UIControlStateNormal];
    
//    [self.sliderView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderViewGrestureRecognizer:)]];
}

- (void)sliderViewGrestureRecognizer:(UITapGestureRecognizer *)recognizer
{
    NSLog(@"点击了sliderView");
}

// 设置模糊效果
- (void)setupTabBar
{
//    self.albumImageView.image = [UIImage imageNamed:@"lkq.jpg"];
    UIToolbar *tabBar = [[UIToolbar alloc] init];
    [self.albumImageView addSubview:tabBar];
    tabBar.barStyle = UIBarStyleBlack;
    tabBar.translatesAutoresizingMaskIntoConstraints = NO;
    
    [tabBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.albumImageView);
    }];
}

// 设置图片圆角
- (void)viewWillLayoutSubviews
{
//    self.iconImageView.image = [UIImage imageNamed:@"lkq.jpg"];
    self.iconImageView.layer.cornerRadius = self.iconImageView.frame.size.width / 2;
    self.iconImageView.layer.masksToBounds = YES;
}


#pragma mark - 定时器相关方法

- (void)addLrcsTimer
{
    self.lrcsTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrcsTimer)];
    [self.lrcsTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)updateLrcsTimer
{
    
    self.LrcsScrollerView.currentTime = self.player.currentTime;
    
}

- (void)removeLrcsTimer
{
    [self.lrcsTimer invalidate];
    self.lrcsTimer = nil;
}

/**
 *  进度条定时器
 */
- (void)addTimer
{
    [self starTimer];
    self.slideTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(starTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.slideTimer forMode:NSRunLoopCommonModes];
}


// 改变播放时间 以及 进度条
- (void)starTimer
{
    
    self.currenTimeLabel.text = [NSString intervalWithTime:round(self.player.currentTime)];
    self.sliderView.value = self.player.currentTime / self.player.duration;
    
    
}

// 移除定时器
- (void)removerTimer
{
    [self.slideTimer invalidate];
    self.slideTimer = nil;
}


#pragma mark - sliderView的事件
// 开始滑动
- (IBAction)sliderBegin {
    
    NSLog(@"removertimer");
    [self removerTimer];
}
// 滑动中
- (IBAction)sliding {
    // 更新当前播放时间
    NSTimeInterval currentTime = round(self.sliderView.value * self.player.duration);
    
    // 根据当前时间计算  播放时间label上的显示文字
    self.currenTimeLabel.text = [NSString intervalWithTime:currentTime];
}
// 滑动结束
- (IBAction)sliderEnd {
    NSTimeInterval currentTime = self.sliderView.value * self.player.duration;
    self.player.currentTime = currentTime;
    self.currenTimeLabel.text = [NSString intervalWithTime:currentTime];
    
    [self addTimer];
}

#pragma mark - 音乐暂停 播放 事件

- (IBAction)musicPlayAndPause:(UIButton *)btn {
    
    btn.selected = !btn.selected;
    if (self.player.isPlaying) {
        [self.player pause];
        [self removerTimer];
        [self removeLrcsTimer];
        
        [self.iconImageView.layer pauseAnimate];
    } else {
        [self.player play];
        
        [self addTimer];
        [self addLrcsTimer];
        [self.iconImageView.layer resumeAnimate];
    }
}


#pragma mark - 切换歌曲

// 下一首
- (IBAction)next:(UIButton *)sender {
    // 停止当前音乐
    MusicInfoModel *currentMusicModel = [GetMusicTool returnPlayingMusic];
    [playMusicTool stopMusic:currentMusicModel.filename];
    
    [self removerTimer];
    
    // 取出下一首歌的数据模型
    [GetMusicTool nextMusic];
    
    // 开始播发
    [self playCurrentMusic];
    
    
    // 回复动画
    [self.iconImageView.layer resumeAnimate];
}

// 上一首
- (IBAction)previous:(UIButton *)sender {
    // 取出当前的音乐模型 停止播放
    MusicInfoModel *model = [GetMusicTool returnPlayingMusic];
    
    // 根据模型里的数据,把音乐名传到，在工具类里面，停止播放
    [playMusicTool stopMusic:model.filename];
    [self removerTimer];
    self.player = nil;
    
    [GetMusicTool previousMusic];
    
    [self playCurrentMusic];
    

    // 回复动画
    [self.iconImageView.layer resumeAnimate];

}



@end
